
from fastapi import APIRouter,Depends

from backend.app.app.crud_pro.tb_userpro_input import *
from backend.app.app.models.project import input_query_require,user_id
from backend.app.app.models.project_data import input_data,out_data
from backend.app.app.api.calculation.evaluation_calculation import *
from backend.app.app.api.api_v1.user import verify_token_user

input_router = APIRouter(prefix="/input", tags=["输入数据"])

@input_router.post("get_pro_id",name="获取用户最新的project_id")
async def get_pro_id(id:user_id,ver = Depends(verify_token_user)):   #          ,"verify":ver
    pro_d = []
    pro_id = get_proId_by_user_id(user_id=id.user_id)
    for i in pro_id:
        if i not in pro_d:
            pro_d.append(i[0])
    return {"user_id":id.user_id,"project_id":pro_d,"verify":ver}

@input_router.post("/read_lib",name="读库之后查询")
async  def read_lib(query_criteria:input_query_require,ver = Depends(verify_token_user)):
    query_inf = get_all_data(query_criteria.name,query_criteria.type,query_criteria.start_year,query_criteria.end_year)
    oil_inf = query_oil(query_criteria.name,start_year=query_criteria.start_year,end_year=query_criteria.end_year)
    ratio_inf = query_ratio(query_criteria.name,start_year=query_criteria.start_year,end_year=query_criteria.end_year)

    return {"query_result":query_inf,"oil_info":oil_inf,"ratio_info":ratio_inf,"verify":ver}


@input_router.post("/get_name_year_type",name="获取开发名称，年度，措施类型")
async  def get_name_year_type(ver=Depends(verify_token_user)): #
    DvpUnit_Name, StimType_Name, Year = get_name_year()
    return {"DvpUnit_Name": DvpUnit_Name, "type": StimType_Name, "year": Year, "verify": ver}

@input_router.post("/save_lib",name="存库")
async def save_lib(inputdata:input_data, ver=Depends(verify_token_user)):
    delete_result = delete_dvp_oil_result(inputdata.delete)
    if inputdata.data:
        result = input_add(inputdata.data)
    else:
        result = {}
    if inputdata.ratio:
        ratio = oilsalecost_ratio(inputdata.ratio)
    else:
        ratio = {}
    if inputdata.oilcost:
        oilcost = oilprodcost(inputdata.oilcost)
    else:
        oilcost = {}
    return {
        'result': result,
        'oilcost': oilcost,
        'ratio': ratio,
        'delete_result': delete_result,
        'verify': ver
    }



@input_router.post("/calculation", name="计算")   #
async def calculation(alldata:out_data,ver = Depends(verify_token_user)):
    result = []
    user_d = []
    all_pro_id = []
    for data in alldata.input_d:
        if data :
            """
            {"User_ID":"str","Proj_ID":"str","DvpUnit_Name":"str","Year":"str",
                       "StimType_Name":"str","Stim_WellNumber_Valid":"int","Stim_WellValidRatio":"float","Stim_ValidPeriod_Average":"float",
                       "Stim_IncreOil_Average":"float","StimCost_Average":"float","Oil_OprCost":"float","Oil_Price":"float",
                       "StimOil_CommodityRatio":"float","OilSale_TotalTaxRatio":"float","Money_Discount":"float","Remark":"str"}
                前端：user_id,pro_id,单元名称，年度，
                措施类别，有效井次，有效率，平均有效期，
                平均措施增油,平均作业成本，操作吨油成本,平均油价，
                原油商品率，平均销售税费率，资金贴现率，备注
            """
            # 1.计算平均增油操作成本
            WellOprCost = wellOprCost(IncreOil=float(data["Stim_IncreOil_Average"]),OilOprCost=float(data["Oil_OprCost"]))

            # 2.计算平均增油毛收入
            GrossSalesIncome = grossSalesIncome(OilPrice=float(data["Oil_Price"]),OilCommodityRatio=float(data["StimOil_CommodityRatio"]),IncreOil=float(data["Stim_IncreOil_Average"]))

            # 3.计算平均销售税费
            TotalTax = totalTax(GrossSalesIncome=GrossSalesIncome,TotalTaxRatio=float(data["OilSale_TotalTaxRatio"]))

            # 4.平均静态收益（元/井）：StaticGains
            StaticGains = staticGains(StimCost=float(data["StimCost_Average"]),WellOprCost=WellOprCost, TotalTax=TotalTax,GrossSalesIncome=GrossSalesIncome)

            # 5.平均财务净现值（元/井）：StimNPV
            # ValidPeriod = 123 #有效天  未找到，临时使用
            # 直接计算StaticGainsPy, 后续需要使用
            ValidPeriod = float(data["Stim_ValidPeriod_Average"])
            ValidYears = math.ceil(ValidPeriod / 365)
            ic = float(data["Money_Discount"]) / 100
            StaticGainsPy_by_count = staticGainsPy(IncreOil=float(data["Stim_IncreOil_Average"]),ValidYears=ValidYears,OilPrice=float(data["Oil_Price"]),OilCommodityRatio=float(data["StimOil_CommodityRatio"]),TotalTaxRatio=float(data["OilSale_TotalTaxRatio"]),OilOprCost=float(data["Oil_OprCost"]))
            StimNPV = evaluation_calculation5(ValidYears=ValidYears,StaticGainsPy=StaticGainsPy_by_count,ic=ic,StimCost=float(data["StimCost_Average"]))

            # 6.投资利润率（%）：StimROI
            StimROI = evaluation_calculation6(StaticGains=StaticGains,StimCost=float(data["StimCost_Average"]))

            # 7.财务净现值率（%）：
            StimNPVR = evaluation_calculation7(StimNPV=StimNPV,StimCost=float(data["StimCost_Average"]))

            # 8.财务内部收益率（%）：StimFIRR
            # ValidPeriod = data["Stim_ValidPeriod_Average"]
            # ValidYears = math.ceil(ValidPeriod / 365)
            StimFIRR = evaluation_calculation8(ValidYears=ValidYears,StimCost=float(data["StimCost_Average"]),StaticGainsPy=StaticGainsPy_by_count)


            # 9.平均经济临界增油量（吨/井）：IncreOilCritical
            # ic = data["Money_Discount"]/100
            IncreOilCritical = evaluation_calculation9(ValidYears=ValidYears,ic=ic,StimCost=float(data["StimCost_Average"]),OilPrice=float(data["Oil_Price"]),OilOprCost=float(data["Oil_OprCost"]),OilCommodityRatio=float(data["StimOil_CommodityRatio"]),TotalTaxRatio=float(data["OilSale_TotalTaxRatio"]))

            # 10.平均经济临界油价（元/吨）：OilPriceCritical
            increOilPy = float(data["Stim_IncreOil_Average"]) / ValidYears
            OilPriceCritical = evaluation_calculation10(ValidYears=ValidYears,ic=ic,StimCost=float(data["StimCost_Average"]),IncreOilPy=increOilPy,OilOprCost=float(data["Oil_OprCost"]),OilCommodityRatio=float(data["StimOil_CommodityRatio"]),TotalTaxRatio=float(data["OilSale_TotalTaxRatio"]))

            # 把所有处理完的数据添加到结果
            temp1 = {
                "WellOprCost":WellOprCost,
                "TotalTax":TotalTax,
                "GrossSalesIncome":GrossSalesIncome,
                "StaticGains": StaticGains,
                "StimNPV":StimNPV,
                "StimROI":StimROI,
                "StimNPVR":StimNPVR,
                "StimFIRR":StimFIRR,
                "IncreOilCritical":IncreOilCritical,
                "OilPriceCritical": OilPriceCritical
            }
            temp_all = dict(data,**temp1)
            result.append(temp_all)
            if data["User_ID"] not in user_d:
                user_d.append(data["User_ID"])
                pro_id = get_proId_by_user_id(data["User_ID"])
                if pro_id:
                    pro_id = pro_id[0]
                temp = {"user_id":data["User_ID"],"project_id":pro_id}
                all_pro_id.append(temp)
        print(all_pro_id)

    return {"result":result,"all_project":all_pro_id,"verify":ver} #    "project_data":alldata,

    """
    前端：user_id,pro_id,单元名称，年度，措施类别，有效井次，有效率，平均有效期，平均措施增油
    ,平均作业成本，操作吨油成本,平均油价，原油商品率，平均销售税费率，资金贴现率，备注
    
    计算后的数据：user_id,pro_id,单元名称，年度，措施类别，有效井次，有效率，平均有效期，平均措施增油，
    平均油价，原油商品率，平均销售税费率,资金贴现率，操作吨油成本,平均作业成本，备注
    平均增油操作成本,平均销售税费，平均增油毛收入，平均静态收益，平均财务净现值，投资利润率，财务净现值率，财务内部收益率，平均临界增油量，经济临界油价
    """


# @input_router.post("/read_Plan_Unit_Year", name="获取计划、单元、年度")
# async def Plan_Unit_Year(ver=Depends(verify_token_user)):
#     try:
#         a = read_Plan_Unit_Year()
#         return {"result": a, "verify": ver}
#     except Exception as e:
#         print(e)
#         return False


